# apps/exam_papers/views.py
from rest_framework import viewsets, permissions, filters, status
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import get_object_or_404

from .models import ExamPaper
from .permissions import IsAuthenticatedOrReject
from .serializers import (
    ExamPaperListSerializer,
    ExamPaperDetailSerializer,
    ExamPaperCreateUpdateSerializer,
    ExamPaperSerializer  # 默认兜底
)
from apps.users.permissions import IsOwnerOrReadOnly  # 自定义权限（见下文）
from ..common.mixins import TenantViewSetMixin


class ExamPaperViewSet(TenantViewSetMixin, viewsets.ModelViewSet):
    """
    试卷视图集
    提供完整的 CRUD 接口：
    - GET /exam_papers/              → 列表
    - GET /exam_papers/{id}/         → 详情
    - POST /exam_papers/             → 创建
    - PUT/PATCH /exam_papers/{id}/   → 更新
    - DELETE /exam_papers/{id}/      → 删除
    - POST /exam_papers/{id}/publish → 发布试卷
    - POST /exam_papers/{id}/archive → 归档试卷
    """

    queryset = ExamPaper.objects.all().select_related('creator', 'subject')
    filter_backends = [
        DjangoFilterBackend,
        filters.SearchFilter,
        filters.OrderingFilter,
    ]
    filterset_fields = {
        'status': ['exact', 'in'],
        'subject': ['exact'],
        'difficulty': ['exact', 'gte', 'lte'],
        'creator': ['exact'],
    }
    search_fields = ['title', 'description']
    ordering_fields = ['created_at', 'updated_at', 'total_score', 'difficulty']
    ordering = ['-created_at']
    permission_classes = [IsAuthenticatedOrReject, IsOwnerOrReadOnly]

    def get_serializer_class(self):
        """
        根据不同动作返回不同的序列化器
        """
        if self.action == 'list':
            return ExamPaperListSerializer
        elif self.action == 'retrieve':
            return ExamPaperDetailSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return ExamPaperCreateUpdateSerializer
        return ExamPaperSerializer

    def get_queryset(self):
        """
        用户只能看到自己的试卷（可选：管理员可看全部）
        可根据需求取消注释
        """
        user = self.request.user
        # 管理员可查看所有
        if user.is_superuser:
            return self.queryset
        # 普通用户只能查看自己的试卷
        return self.queryset.filter(creator=user)

    def perform_create(self, serializer):
        """
        创建时自动设置 creator 为当前用户
        （即使 serializer 中已处理，这里再确保一次）
        """
        user = self.request.user
        if not user.tenant:
            raise PermissionDenied("无法创建试卷：当前用户未分配租户。")
        serializer.save(creator=user, tenant=user.tenant)

    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def publish(self, request, pk=None):
        """
        自定义动作：发布试卷
        URL: POST /exam_papers/{id}/publish/
        """
        exam_paper = self.get_object()
        if exam_paper.status == 'published':
            return Response(
                {'detail': '试卷已发布，无需重复操作。'},
                status=status.HTTP_400_BAD_REQUEST
            )
        if exam_paper.status == 'archived':
            return Response(
                {'detail': '归档试卷无法发布，请先恢复。'},
                status=status.HTTP_400_BAD_REQUEST
            )

        exam_paper.status = 'published'
        exam_paper.save(update_fields=['status', 'updated_at'])
        return Response({'status': '已发布', 'id': exam_paper.id}, status=status.HTTP_200_OK)

    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def archive(self, request, pk=None):
        """
        自定义动作：归档试卷
        URL: POST /exam_papers/{id}/archive/
        """
        exam_paper = self.get_object()
        if exam_paper.status == 'archived':
            return Response(
                {'detail': '试卷已归档。'},
                status=status.HTTP_400_BAD_REQUEST
            )

        exam_paper.status = 'archived'
        exam_paper.save(update_fields=['status', 'updated_at'])
        return Response({'status': '已归档', 'id': exam_paper.id}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'], permission_classes=[permissions.AllowAny])
    def public(self, request):
        """
        获取所有已发布的试卷（公开访问）
        URL: GET /exam_papers/public/
        """
        published_papers = ExamPaper.objects.filter(status='published') \
            .select_related('creator', 'subject') \
            .values('id', 'title', 'total_score', 'duration_minutes', 'difficulty', 'created_at') \
            .order_by('-created_at')

        page = self.paginate_queryset(published_papers)
        if page is not None:
            serializer = ExamPaperListSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = ExamPaperListSerializer(published_papers, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['get'], permission_classes=[permissions.AllowAny])
    def stats(self, request, pk=None):
        """
        获取试卷统计信息（如：参与人数、平均分等）
        模拟接口，实际需关联考试记录
        URL: GET /exam_papers/{id}/stats/
        """
        exam_paper = get_object_or_404(ExamPaper, id=pk, status='published')

        # TODO: 此处应查询考试记录表（如 ExamRecord）获取真实数据
        mock_stats = {
            'paper_id': exam_paper.id,
            'title': exam_paper.title,
            'total_score': float(exam_paper.total_score),
            'attempts_count': 128,
            'average_score': 76.5,
            'pass_rate': '78.1%',
            'highest_score': 98.0,
            'lowest_score': 42.0,
            'updated_at': exam_paper.updated_at
        }
        return Response(mock_stats)